package com.hsj.springai.controller;

import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("openai")
public class OpenAiController {

    @Autowired
    private OpenAiChatModel openAiChatModel;

    private final ChatClient chatClient;

    public OpenAiController(ChatClient.Builder chatClientBuilder) {
        this.chatClient = chatClientBuilder.build();
    }

    @GetMapping("string")
    public String chat01(@RequestParam(value = "message", defaultValue = "介绍一下自己") String message) {
        return openAiChatModel.call(message);
    }

    @GetMapping("response")
    public String chat02(@RequestParam(value = "message", defaultValue = "介绍一下中国") String message) {
        Prompt prompt = new Prompt(message + "123");
        ChatResponse response = openAiChatModel.call(prompt);
        return response.getResult().getOutput().getContent();
    }

    //要处理 乱码问题
    @GetMapping(value = "flux", produces = "text/html;charset=utf-8")
    public Flux<String> chat03(@RequestParam(value = "message", defaultValue = "介绍一下中国") String message) {
        Flux<String> stream = openAiChatModel.stream(message);
        return stream;
    }

    /**
     * record关键字 创建 密封类 密封类里的字段不可再被修改，相当于所有的字段都加了final修饰
     */
    record ActorFilms(String actor, List<String> movies) {  //小括号里是 他的属性 及 属性名
    }

    @GetMapping("/entity")
    public ActorFilms entity(@RequestParam(value = "message", defaultValue = "Generate the filmography for a random actor.") String message) {
        ActorFilms actorFilms = chatClient.prompt()
                .user(message)  //设置提示词
                .call()                         //调方法
                .entity(ActorFilms.class);    //制定返回值的类型
        return actorFilms;
    }
}
